package com.mt.mtbletools;

import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import com.mt.help.GlobalVariable;
import com.mt.mtbletools.R;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.tools.MTTools;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AdvertisementActivity extends Activity {

	public static final String SELECTDEVICE = "SELECTDEVICE";
	private GlobalVariable mGlobalVariable;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_advertisement);
		mGlobalVariable = GlobalVariable.getinstance();
		
		initView();

		getDefaultDatas();
	}

	// 初始化控件
	private TextView total_txt;
	private TextView analysis_txt;
	private Button goback_btn;
	private Button connect_btn;

	private void initView() {
		total_txt = (TextView) findViewById(R.id.total_txt);
		analysis_txt = (TextView) findViewById(R.id.analysis_txt);

		goback_btn = (Button) findViewById(R.id.goback_btn);
		connect_btn = (Button) findViewById(R.id.connect_btn);

		goback_btn.setOnClickListener(MyonClickListener);
		connect_btn.setOnClickListener(MyonClickListener);
	}

	// 获取传递数据
	private MTBLEDevice device;
	private int index;
	private void getDefaultDatas() {
		index  = getIntent().getIntExtra(ScanFragment.SELECTDEVICE, -1);
		if(index == -1){
			finish();
			return;
		}
		if(mGlobalVariable.getDeviceList().size() == 0){
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);

		// ****************显示全部广播数据
		total_txt.setText(MTTools.convertBytearrayToString(device.getScanRecord()).toUpperCase(Locale.getDefault()));

		// ****************显示分析出来的数据
		Iterator iter = device.getRecordMap().entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Byte key = (Byte) entry.getKey();
			byte[] val = (byte[]) entry.getValue();

			analysis_txt.append(MTTools.convertByteToString(key.byteValue()).toUpperCase(Locale.getDefault()) + "(L:"
					+ val.length + ")" + MTTools.convertBytearrayToString(val).toUpperCase(Locale.getDefault()) + "("
					+ new String(val) + ")" + "\r\n");
		}
	}

	// 按键操作
	private OnClickListener MyonClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == goback_btn) {
				finish();
				return;
			}

			if (v == connect_btn) {
				Intent intent = new Intent(AdvertisementActivity.this, BaseBleActivity.class);
				intent.putExtra(SELECTDEVICE, index);
				startActivity(intent);
				return;
			}
		}
	};
}
